package commonInfrastructure.communication;

import entity.Message;
import java.sql.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class MessageSession implements MessageSessionRemote {

    @PersistenceContext
    private EntityManager entityManager;
    
    @Override
    public Long sendMessage(Long staffIDFrom, Long staffIDTo, String message){
        Message m = new Message();
        
        m.setStaffIDFrom(staffIDFrom);
        m.setStaffIDTo(staffIDTo);
        m.setMessage(message);
        m.setIsRead(false);
        
        java.util.Calendar cal = java.util.Calendar.getInstance();
        java.util.Date utilDate = cal.getTime();
        java.sql.Date sqlDate = new Date(utilDate.getTime());
        m.setSendTime(sqlDate);
        
        entityManager.persist(m);
        entityManager.flush();
        
        return m.getMessageID();
    }
    
    @Override
    public void setRead(Long messageID){
        Message m = entityManager.find(Message.class, messageID);
        m.setIsRead(true);
        entityManager.flush();
    }
    
    //Get all message froo A to B, sort from newest to oldest
    @Override
    public List<Message> getMessage(Long staffIDFrom, Long staffIDTo){
        String strQuery = "SELECT m FROM Message m where m.staffIDFrom = :inStaffIDFrom AND m.staffIDTo = :inStaffIDTo ORDER BY m.messageID";
        Query query =  entityManager.createQuery(strQuery);
        query.setParameter("inStaffIDFrom", staffIDFrom);
        query.setParameter("inStaffIDTo", staffIDTo);        
        
        return query.getResultList();
    }
    
    @Override
    public List<Message> getAllUnread(Long staffIDTo){
        String strQuery = "SELECT m FROM Message m where m.staffIDTo = :inStaffIDTo AND m.isRead = false ORDER BY m.staffIDFrom";
        Query query =  entityManager.createQuery(strQuery);
        query.setParameter("inStaffIDTo", staffIDTo);
        
        return query.getResultList();
    }
    
    @Override
    public void deleteMessage(Long id){
        Message m = entityManager.find(Message.class, id);
        entityManager.remove(m);
        entityManager.flush();
    }
}